package com.mao.shiro_jsp.config;

import com.mao.shiro_jsp.cache.RedisCacheManager;
import com.mao.shiro_jsp.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 小毛同学
 * @version 1.0
 * @data 2021/12/30 9:59
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //设置过滤器
        Map<String,String> map = new HashMap<>();
        //设置受限资源
        map.put("/index.jsp","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //设置认证界面路径  受限资源被拦截后跳转的路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        return shiroFilterFactoryBean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(CustomerRealm customerRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public CustomerRealm getCustomerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        // 修改凭证校验匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");  // 设置加密算法为md5
        hashedCredentialsMatcher.setHashIterations(1024);      // 设置散列次数
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);


        // 开启缓存管理
        customerRealm.setCacheManager(new RedisCacheManager());
        customerRealm.setCachingEnabled(true); // 开启全局缓存
        customerRealm.setAuthenticationCachingEnabled(true); // 开启认证缓存
        customerRealm.setAuthenticationCacheName("authenticationCache");
        customerRealm.setAuthorizationCachingEnabled(true); // 开启缓存缓存
        customerRealm.setAuthorizationCacheName("authorizationCache");
        return customerRealm;
    }
}
